package io.knifer.gokexceltask.utils;

import io.knifer.gokexceltask.pojo.domain.ResultInfo;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class RIUtils {
    private RIUtils() {
        throw new RuntimeException();
    }

    public static ResultInfo<Void> createOK(){
        return new ResultInfo<>(200, null, null);
    }

    public static<T> ResultInfo<T> create(Integer code, String msg, T data){
        return new ResultInfo<>(code, msg, data);
    }

    public static void sendFile(File file, HttpServletResponse response) throws IOException {
        sendFile(file, file.getName(), response);
    }

    public static void sendFile(File file, String fileName, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        response.setContentType("multipart/form-data");
        response.setContentLength((int) file.length());
        response.setCharacterEncoding("UTF-8");
        response.getOutputStream().write(FileCopyUtils.copyToByteArray(file));
    }

    public static void send(String content, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.getOutputStream().write(content.getBytes(StandardCharsets.UTF_8));
    }
}
